<?php defined('SYSPATH') OR die('No direct access allowed.');

class cms {

	public function __construct() {
		Event::add('admin.access_denied', array($this, 'show_403'));
		Event::replace('system.404', array('Kohana', 'show_404'), array($this, 'show_404'));
    Event::add('system.ready', array($this, 'fill_configs'));
		//Event::add('system.display', array($this, 'prepare_lang'));
		Event::add('system.ready', array('message', 'init'));
		Event::add('system.send_headers', array('message', 'save'));
		Event::add('system.redirect', array('message', 'save'));
		Event::add('cms.captcha.ban', array($this, 'ban'));
		Event::add('system.post_controller', array($this, 'history'));
		Event::add('cms.header.render', array($this, 'show_modules'));
	}

	public function show_403() {
		header('HTTP/1.1 403 Forbidden');
		if (is_null(Kohana::$instance)) {
			Kohana::$instance = new Error_Controller;
			Kohana::$instance->template->header = '';
			Kohana::$instance->template->footer = '';
		}
		Kohana::$instance->template->page = new View('403');
		Kohana::$instance->template->title = Kohana::lang('admin.access_denied');
    Kohana::$instance->template->render(TRUE);
    die();
	}

	public function show_404() {
		header('HTTP/1.1 404 File Not Found');
		if (is_null(Kohana::$instance)) {
			Kohana::$instance = new Error_Controller;
			Kohana::$instance->template->header = '';
			Kohana::$instance->template->footer = '';
		}
		Kohana::$instance->template->page = new View('404');
		Kohana::$instance->template->title = Kohana::lang('admin.file_not_found');
    Kohana::$instance->template->render(TRUE);
    die();
	}

  public function fill_configs() {
    // смотрим все конфиги БД и если каких-то полей нет, дополняем их default'ными
    $configs = Kohana::config('database');
    $default_size = count($configs['default']);
    $default_connection_size = count($configs['default']['connection']);
    $default_prefix = strlen($configs['default']['table_prefix']) > 0 ? $configs['default']['table_prefix'] : FALSE;
    foreach ($configs as $name => $config) {
      if ($name === 'default') continue;
      if (count($config) != $default_size) {
        $newconfig = arr::overwrite($configs['default'], $config);
        // Для префиксов придется сделать исключение
        $default_prefix !== FALSE AND $newconfig['table_prefix'] = $default_prefix.$newconfig['table_prefix'];
      }
      if (!isset($config['connection'])) {
        $newconnection = $configs['default']['connection'];
      }
      elseif (count($config['connection']) != $default_connection_size) {
        $newconnection = arr::overwrite($configs['default']['connection'], $config['connection']);
      }
      isset($newconfig) AND Kohana::config_set('database.'.$name, $newconfig);
      isset($newconnection) AND Kohana::config_set('database.'.$name.'.connection', $newconnection);
    }
  }

	public function prepare_lang() {
		// Заменяем все куски вида {LANG_xxxxx} на результат работы Kohana::lang(xxxxx)
		// todo: предусмотреть возможность подстановки значений.
		$begin = 0;
		$matches = array();
		$replaces = array();
		while(FALSE !== ($begin = strpos(Event::$data, "{{", $begin))) {
			if (FALSE === ($end = strpos(Event::$data, "}}", $begin+2))) {
				break;
			}
			$lang_text = substr(Event::$data, $begin+7, $end-$begin-7);
			if (preg_match('/^[a-z0-9_.]++$/iD', $lang_text) == FALSE OR in_array('{{LANG_'.$lang_text.'}}', $matches)) {
				$begin++;
				continue;
			}
			$matches[] = '{{LANG_'.$lang_text.'}}';
			$replaces[] = Kohana::lang($lang_text);
			$begin += strlen($lang_text) + 9;
			/*if ($begin >= strlen(Event::$data))
				break;*/
		}
		Event::$data = str_replace($matches, $replaces, Event::$data);
	}

	public function ban() {
		// баним за перебор нераскрытых каптч за сессию
		if ($user = A2::instance()->get_user()) {
			$user->ban();
		}
		Kohana::$instance = new Error_Controller;
		Kohana::$instance->template->page = new View('banned');
		Kohana::$instance->template->title = Kohana::lang('admin.banned');
    Kohana::$instance->template->render(TRUE);
    die();
	}

	public function history() {
		if (Kohana::$instance instanceof Frontend_Controller)
			Kohana::$instance->_keep_referrer(TRUE);
	}

	public function show_modules() {
		$modname = mmanager::current();
		//if ($modname == 'default') $modname = 'main';
		if (!Kohana::config($modname.'.show_modules')) return;
		View::factory('layout/module_nav')->set('current', $modname)->render(TRUE);
	}
}

new cms;